import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'model/scheme_info_detail_data.dart';
import 'model/trtc_auth_info_data.dart';

typedef void AnswerCreatedCallback(AnswerController controller);

class Answer extends StatefulWidget {
  static const MethodChannel _channel = const MethodChannel('flutter_plugin');
  static Future<String> get platformVersion async {
    final String version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  const Answer({
    Key key,
    this.onAnswerCreated,
    this.schemeInfoDetailData,
    this.schemeId,
    this.roomId,
    this.headUrl,
    this.name,
    this.userId,
    this.accountId,
    this.vrType,
    this.groupId,
    this.token,
    this.trtcAuthInfoData,
  });

  final AnswerCreatedCallback onAnswerCreated;
  final SchemeInfoDetailData schemeInfoDetailData;
  final int schemeId;
  final int roomId;
  final String headUrl;
  final String name;
  final int userId;
  final int accountId;
  final int vrType;
  final String groupId;
  final String token;
  final TrtcAuthInfoData trtcAuthInfoData;

  @override
  _AnswerState createState() => _AnswerState();
}

class _AnswerState extends State<Answer> {
  @override
  Widget build(BuildContext context) {
    if (defaultTargetPlatform == TargetPlatform.android) {

      var schemeInfoDetailDataMap = widget.schemeInfoDetailData.toJson();
      var schemeInfoDetailDataJson = json.encode(schemeInfoDetailDataMap);
      print(schemeInfoDetailDataJson);

      return AndroidView(
        viewType: 'plugins.com.asman/answer',
        onPlatformViewCreated: _onPlatformViewCreated,
        layoutDirection: TextDirection.ltr,
        creationParams: <String,dynamic>{
          "schemeInfoDetailData": schemeInfoDetailDataJson,
          "schemeId": widget.schemeId,
          "roomId": widget.roomId,
          "headUrl": widget.headUrl,
          "name": widget.name,
          "userId": widget.userId,
          "accountId": widget.accountId,
          "vrType": widget.vrType,
          "groupId": widget.groupId,
        },
        creationParamsCodec: StandardMessageCodec(),
      );
    }
    if (defaultTargetPlatform == TargetPlatform.iOS) {
      final kScreenHeight = MediaQuery.of(context).size.height;
      var schemeInfoDetailDataMap = widget.schemeInfoDetailData.toJson();
      var schemeInfoDetailDataJson = json.encode(schemeInfoDetailDataMap);
      print(schemeInfoDetailDataJson);
      print("widget user id is : ${widget.userId}");
      print("trtc user id is : ${widget.trtcAuthInfoData.userId}");
      return Container(
        height: kScreenHeight,
        child: UiKitView(
          viewType: "plugins.com.asman/answer",
          creationParams: <String,dynamic>{
            "schemeInfoDetailData": schemeInfoDetailDataJson,
            "schemeId": widget.schemeId,
            "roomId": widget.roomId,
            "headUrl": widget.headUrl,
            "name": widget.name,
            "userId": widget.trtcAuthInfoData.userId,
            "accountId": widget.accountId,
            "vrType": widget.vrType,
            "groupId": widget.groupId,
            "token": widget.token,
            "sdkAppId": widget.trtcAuthInfoData.sdkAppId,
            "userSig": widget.trtcAuthInfoData.userSig,
          },
          creationParamsCodec: StandardMessageCodec(),
          onPlatformViewCreated: _onPlatformViewCreated,
        ),
      );
    }
    return Text("目前只提供安卓和 ios 平台支持，其他平台等待实现");
  }

  void _onPlatformViewCreated(int id) {
    if (widget.onAnswerCreated == null) {
      return;
    }
    widget.onAnswerCreated(new AnswerController._(id));
  }
}

class AnswerController {
  AnswerController._(int id)
      : _channel = new MethodChannel('plugins.com.asman/answer_$id');

  final MethodChannel _channel;

  Function onGoBack;
  Function router3DRoam;
  Function rejectAnswer;
  Function getTrtcAuthInfo;
  Function notifyDesignerJoined;
  Function canReceived;

  Future<dynamic> _addNativeMethod(MethodCall methodCall) async {
    switch (methodCall.method) {
      case "onGoBack":
        onGoBack();
        break;
      case "router3DRoam":
        router3DRoam();
        break;
      case "rejectAnswer":
        rejectAnswer();
        break;

      case "getTrtcAuthInfo":
        getTrtcAuthInfo();
        break;

      case "notifyDesignerJoined":
        notifyDesignerJoined();
        break;

      case "canReceived":
        String callbackName = methodCall.arguments;
        var cbArr = callbackName.split(",");
        checkRoomStatus(cbArr[0], cbArr[1], cbArr[2]);
        break;

      case "answer":
        String callbackName = methodCall.arguments;
        var cbArr = callbackName.split(",");
        answer(cbArr[0], cbArr[1], cbArr[2]);
        break;
    }
  }

  void addNativeMethod({
    Function onGoBack,
    Function router3DRoam,
    Function rejectAnswer,
    Function getTrtcAuthInfo,
    Function notifyDesignerJoined,
    Function canReceived,
  }) {
    this.onGoBack = onGoBack;
    this.router3DRoam = router3DRoam;
    this.rejectAnswer = rejectAnswer;
    this.getTrtcAuthInfo = getTrtcAuthInfo;
    this.notifyDesignerJoined = notifyDesignerJoined;
    this.canReceived = canReceived;
    _channel.setMethodCallHandler(_addNativeMethod);
  }

  // 调用原生 flutter 方法
  Future<void> joinRoom({@required bool isSuccess,TrtcAuthInfoData trtcAuthInfoData}) async {
    if(isSuccess){
      var trtcAuthInfoDataMap = trtcAuthInfoData.toJson();
      var trtcAuthInfoDataJson = json.encode(trtcAuthInfoDataMap);
      _channel.invokeMethod('joinRoom_success', trtcAuthInfoDataJson);
    }else {
      _channel.invokeMethod('joinRoom_fail', "请求失败");
    }
  }

  void checkRoomStatus(String validCallbackName, String invalidCallbackName, String errorCallbackName) async {
    try {
      if(await this.canReceived() == true) {
        _channel.invokeMethod(validCallbackName);
      } else {
        _channel.invokeMethod(invalidCallbackName);
      }
    } catch (e) {
      _channel.invokeMethod(errorCallbackName);
    }
  }

  void answer(String validCallbackName, String invalidCallbackName, String errorCallbackName) async {
    try {
      if((await this.canReceived() == true) && (await this.notifyDesignerJoined() == true)) {
        _channel.invokeMethod(validCallbackName);
      } else {
        _channel.invokeMethod(invalidCallbackName);
      }
    } catch (e) {
      _channel.invokeMethod(errorCallbackName);
    }
  }

  // 调用原生的方法，destroy
  Future<void> destroy() async {
    return _channel.invokeMethod('destroy');
  }
}
